﻿#include "bluetoothdev.h"
#include "ui_bluetoothdev.h"
#include <QDebug>
#include <QApplication>
#include <QScreen>
#define debugInfo qDebug()

BluetoothDev::BluetoothDev(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::BluetoothDev)
{
    ui->setupUi(this);
    setWindowTitle("Qt蓝牙通信调试助手");
}

BluetoothDev::~BluetoothDev()
{
    delete ui;
}

void BluetoothDev::newDeviceFinded(const QBluetoothDeviceInfo &info)
{
    QString Dev_name = info.name();
    QString Dev_address = info.address().toString();

    QBluetoothLocalDevice::Pairing pairingStatus = BDevice->pairingStatus(info.address());
    if(pairingStatus == QBluetoothLocalDevice::Paired)
    {
        ui->DevList->addItem(Dev_name + ":" + Dev_address, Dev_address);
    }
    else if(pairingStatus == QBluetoothLocalDevice::Unpaired)  //未配对的设备
    {
        ui->DevList->addItem("*" + Dev_name + ":" + Dev_address, Dev_address);
    }
}
void BluetoothDev::DiscoveryAgentError(QBluetoothDeviceDiscoveryAgent::Error error)
{
    debugInfo<<error;
    QMessageBox::information(this, "提示", BAgent->errorString());
}

void BluetoothDev::statusBarLog(const QString& info)
{
    // ui->statusBar->showMessage(info);
    statusBarLable->setText(info);
}

void BluetoothDev::showEvent(QShowEvent *)
{
    static bool isFirstShow = true;
    if(!isFirstShow)
    {
        return;
    }
    isFirstShow = false;
    ui->menubar->setVisible(true);
    ui->manageSocket->setEnabled(false);
    ui->sendMsg->setEnabled(false);
    statusBarLable = new QLabel(this);
    statusBarLable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    statusBarLable->setAlignment(statusBarLable->alignment() | Qt::AlignHCenter);
    ui->statusBar->addWidget(statusBarLable);

    sendGroup.addButton(ui->rb_sendAscii, 0);
    sendGroup.addButton(ui->rb_sendHex, 1);

    reciveGroup.addButton(ui->rb_reciveAscii, 0);
    reciveGroup.addButton(ui->rb_reciveHex, 1);

    MessageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    MessageBox.setDefaultButton(QMessageBox::Yes);

    BDevice = new QBluetoothLocalDevice(this);
    if(BDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff)
    {
        MessageBox.setText("蓝牙设备已关闭，现在打开吗？");
        int ret = MessageBox.exec();
        if(ret == QMessageBox::Yes)
        {
            BDevice->powerOn();
            statusBarLog("蓝牙状态：打开");
        }
        statusBarLog("蓝牙状态：关闭");
    }
    else
    {
        statusBarLog("蓝牙状态：打开");
    }
    connect(BDevice, &QBluetoothLocalDevice::pairingFinished, this, &BluetoothDev::pairFinish);
    connect(BDevice, &QBluetoothLocalDevice::error, this, &BluetoothDev::localDevError);

    BAgent = new QBluetoothDeviceDiscoveryAgent(this);
    connect(BAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &BluetoothDev::newDeviceFinded);
    connect(BAgent, &QBluetoothDeviceDiscoveryAgent::finished, [this]{
        statusBarLog("搜索结束");
        ui->manageSocket->setEnabled(true);
    });
    connect(BAgent, &QBluetoothDeviceDiscoveryAgent::canceled, [this]{
        statusBarLog("停止搜索蓝牙设备");
        ui->manageSocket->setEnabled(true);
    });
    connect(BAgent, SIGNAL(error), this, SLOT(DiscoveryAgentError));
    BSocket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
    connect(BSocket, &QBluetoothSocket::stateChanged, this, &BluetoothDev::socketStateChange);

    timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, &QTimer::timeout, [this]{    socketMsg();    });
    connect(BSocket, &QBluetoothSocket::readyRead, [this]{  timer->start(ReciveDelay);   });

    // ui->textBrowser->setVisible(false);
    QTimer::singleShot(60*1000, this, [=]{
        QMessageBox::warning(this, "提示", "本次试用结束！");
        this->close();
    });
}

void BluetoothDev::on_manageSocket_clicked()
{
    QString Dev_name = ui->DevList->currentText();
    QString Dev_address = ui->DevList->currentData().toString();

    if(BSocket->state() == QBluetoothSocket::SocketState::UnconnectedState)
    {
        if(ui->DevList->currentText().startsWith("*"))
        {
            MessageBox.setText("该蓝牙设备未配对，现在配对吗？");
            int ret = MessageBox.exec();
            if(ret == QMessageBox::Yes)
            {
                statusBarLog("蓝牙配对开始");
                BDevice->requestPairing(QBluetoothAddress(Dev_address), QBluetoothLocalDevice::Paired);
            }
            return;
        }
        statusBarLog("正在连接" + Dev_name);
        BSocket->connectToService(QBluetoothAddress(Dev_address),QBluetoothUuid(serviceUuid));
        return;
    }
    else if(BSocket->state() == QBluetoothSocket::SocketState::ConnectedState)
    {
        BSocket->abort();
    }
}
void BluetoothDev::socketStateChange(QBluetoothSocket::SocketState state)
{
    if(state == QBluetoothSocket::SocketState::UnconnectedState)
    {
        ui->manageSocket->setText("连接");
        ui->sendMsg->setEnabled(false);
        statusBarLog("蓝牙连接断开");
    }
    else if(state == QBluetoothSocket::SocketState::ConnectedState)
    {
        ui->manageSocket->setText("断开");
        ui->sendMsg->setEnabled(true);
        statusBarLog("蓝牙连接成功");
    }
}

void BluetoothDev::on_sendMsg_clicked()
{
    ui->textBrowser->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz   T"));
    QString text = ui->textEdit->toPlainText();
    switch (sendmode)
    {
    case s_ascii:
    {
        BSocket->write(useLocal == useCharSet ? text.toLocal8Bit() : text.toUtf8());
        break;
    }
    case s_hex:
    {
        BSocket->write(QByteArray::fromHex(useLocal == useCharSet ? text.toLocal8Bit() : text.toUtf8()));
        break;
    }
    }
    ui->textBrowser->append(text);
    sendCount += text.length();
    ui->sendCount->setText("累计发送：" + QString::number(sendCount));
}
void BluetoothDev::socketMsg()
{
    ui->textBrowser->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz   R"));
    QByteArray message = BSocket->readAll();
    switch (dispmode)
    {
    case d_ascii:
    {
        ui->textBrowser->append(useLocal == useCharSet ? QString::fromLocal8Bit(message) : QString::fromUtf8(message));
        break;
    }
    case d_hex:
    {
        ui->textBrowser->append(message.toHex(' '));
        break;
    }
    }
    reciveCount += message.length();
    ui->reciveCount->setText("累计接收：" + QString::number(reciveCount));
}

void BluetoothDev::pairFinish(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
    Q_UNUSED(address);
    if(pairing == QBluetoothLocalDevice::Paired)
    {
        ui->DevList->setItemText(ui->DevList->currentIndex(), ui->DevList->currentText().replace("*", "#"));
        ui->DevList->update();
        QMessageBox::information(this, "提示", "蓝牙配对成功");
    }
}

void BluetoothDev::localDevError(QBluetoothLocalDevice::Error error)
{
    if(error == QBluetoothLocalDevice::PairingError)
    {
        QMessageBox::information(this,"提示","配对失败");
    }
    else if(error == QBluetoothLocalDevice::UnknownError)
    {
        QMessageBox::information(this,"提示","配对时发生未知错误");
    }
}

void BluetoothDev::on_actSearchBT_triggered()
{
    if(!BAgent->isActive())
    {
        if(BDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff)
        {
            int ret = MessageBox.exec();
            if(ret == QMessageBox::No)
            {
                statusBarLog("蓝牙状态：关闭");
                return;
            }
            BDevice->powerOn();
            statusBarLog("蓝牙状态：打开");
        }
        else
        {
            statusBarLog("蓝牙状态：打开");
        }
        ui->DevList->clear();
        BAgent->start();
        statusBarLog("正在搜索蓝牙设备");
        ui->manageSocket->setEnabled(false);
    }
}

void BluetoothDev::on_actStopSearch_triggered()
{
    if(BAgent->isActive())  //正在搜索
    {
        BAgent->stop();
    }
    if(ui->DevList->count() > 0)
    {
        ui->manageSocket->setEnabled(true);
    }
}

void BluetoothDev::on_actCloseBT_triggered()
{
    BDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);
    ui->manageSocket->setEnabled(false);
}


void BluetoothDev::on_actHexDisp_triggered()
{
    dispmode = d_hex;
}


void BluetoothDev::on_actHexSend_triggered()
{
    sendmode = s_hex;
}

void BluetoothDev::on_actAsciiDisp_triggered()
{
    dispmode = d_ascii;
}

void BluetoothDev::on_actAsciiSend_triggered()
{
    sendmode = s_ascii;
}

void BluetoothDev::on_actReciveDelay_triggered()
{
    bool ok;
    int value = QInputDialog::getInt(0, "", "Recive Delay ms", ReciveDelay, 0, 10000, 1, &ok);
    if(ok)
    {
        ReciveDelay = value;
    }
}

void BluetoothDev::on_searchSocket_clicked()
{
    if(ui->searchSocket->text().startsWith("搜索"))
    {
        ui->searchSocket->setText("停止");
        on_actSearchBT_triggered();
    }
    else
    {
        ui->searchSocket->setText("搜索");
        on_actStopSearch_triggered();
    }
}

void BluetoothDev::on_rb_sendAscii_clicked()
{
    sendmode = s_ascii;
}


void BluetoothDev::on_rb_sendHex_clicked()
{
    sendmode = s_hex;
}


void BluetoothDev::on_rb_reciveAscii_clicked()
{
    dispmode = d_ascii;
}


void BluetoothDev::on_rb_reciveHex_clicked()
{
    dispmode = d_hex;
}


void BluetoothDev::on_pbt_clearRecive_clicked()
{
    ui->textBrowser->clear();
}


void BluetoothDev::on_pbt_clearCount_clicked()
{
    sendCount = 0;
    ui->sendCount->setText("累计发送：0");
    reciveCount = 0;
    ui->reciveCount->setText("累计发送：0");
}


void BluetoothDev::on_pbt_clearSend_clicked()
{
    ui->textEdit->clear();
}


void BluetoothDev::on_actOpenBT_triggered()
{
    if(BDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff)
    {
        BDevice->powerOn();
    }
}


void BluetoothDev::on_actLocalCharSet_triggered()
{
    useCharSet = useLocal;
}


void BluetoothDev::on_actUTF8CharSet_triggered()
{
    useCharSet = useUtf8;
}

